package com.guanzi.netty.server.handler;

import com.guanzi.netty.message.RpcResponseMessage;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.Promise;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 管子
 * @date 2025/3/17 22:17
 * @description: RpcResponseMessageHandler 类
 */
@ChannelHandler.Sharable
public class RpcResponseMessageHandler extends SimpleChannelInboundHandler<RpcResponseMessage> {

    private static Logger log = LoggerFactory.getLogger(RpcResponseMessageHandler.class);

    /**
     * sequenceId和线程通信（放和取的书包）数据结果 map
     */
    public static Map<Integer, Promise<Object>> PROMISES = new ConcurrentHashMap<>();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcResponseMessage message) throws Exception {
        log.info("收到RPC返回消息: " + message);
        // 获取并删除这个key
        Promise<Object> promise = PROMISES.remove(message.getSequenceId());
        // 处理正确请求和异常请求
        if (promise != null) {
            Object returnValue = message.getReturnValue();
            Exception exceptionValue = message.getExceptionValue();
            if (exceptionValue != null) {
                promise.setFailure(exceptionValue);
            } else {
                promise.setSuccess(returnValue);
            }
        }

    }
}
